package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.stream.CollectorUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService iUserService;

    @Override
    public Result followme(Long id, boolean flag) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;

        //已关注，取关
        if (flag == false) {
            Follow one = query().eq("user_id", id).eq("follow_user_id", userId).one();
            //如果存在就删除
            boolean isSuccess = removeById(one.getId());
            if (isSuccess) {
                stringRedisTemplate.opsForSet().remove(key, id.toString());
            }
            return Result.ok();
        }
        //如果不存在就关注
        Follow follow = new Follow();
        follow.setUserId(id);
        follow.setFollowUserId(userId);
        follow.setCreateTime(LocalDateTime.now());
        boolean isSuccess = save(follow);
        if (isSuccess) {
            stringRedisTemplate.opsForSet().add(key, id.toString());
        }
        return Result.ok();
    }

    @Override
    public Result followOrNot(Long id) {
        Long userId = UserHolder.getUser().getId();
        Follow one = query().eq("user_id", id).eq("follow_user_id", userId).one();
        if (one == null) {
            return Result.ok(false);
        }
        return Result.ok(true);
    }

    @Override
    public Result followEach(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        //1.求交集
        String key2 = "follows:" + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);

        if (intersect == null || intersect.isEmpty()) {
            //无交集
            return Result.ok(Collections.emptyList());
        }
        //2.解析id集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOS = iUserService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }
}
